<?php

namespace App\Http\Controllers\H5;

use App\Models\Item;
use App\Models\PostCatlog;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class SearchController extends BaseController
{
    public function index()
    {

        $catid = $this->request->input('catid');
        $q = $this->request->input('q');

        return $this->view('h5.search', compact('catid', 'q'));
    }

    public function getJson(Request $request)
    {
        $offset = $request->input('offset', 0);
        $count  = $request->input('count', 10);

        $query = Item::onSale();
        $catid = $request->input('catid', 0);
        if ($catid) {
            $catIds = PostCatlog::fetchAllChildIds($catid);
            $query = $query->whereIn('catid', $catIds);
        }

        $q = $request->input('q', '');
        if ($q)
        {
            $query = $query->where('title', 'LIKE', "%$q%");
        }

        $orderby = $request->input('orderby', 'time-desc');
        if ($orderby == 'time-desc')
        {
            $query = $query->orderByDesc('itemid');
        } else {
            $query = $query->orderByDesc('sold');
        }

        $items = $query->offset($offset)->limit($count)
                ->get()->map(function ($item){
                    $item->thumb = image_url($item->thumb);
                    $item->image = image_url($item->image);
                    $item->poster = $item->poster ? image_url($item->poster) : image_url($item->image);
                    return $item;
                });
        return ajaxReturn(['items'=>$items]);
    }
}
